package org.apache.flink.connector.httptm.factories;

import org.apache.flink.connector.httptm.RequestInfo;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 众兴网请求
 */
public class ZhongxingRequestFactory implements RequestFactory {


    @Override
    public String factoryIdentifier() {
        return "zhongxing";
    }

    @Override
    public RequestInfo createRequestInfo(String path, Map<String, String> headers, Map<String, String> params, String body,  Map<String, Object> settings) throws Exception {
        Date curr = new Date();
        Date yest = getYest();
        Map<String, String> format = new HashMap<>();
        format.put("currDay", new SimpleDateFormat("yyyyMMdd").format(curr));
        format.put("yestDay", new SimpleDateFormat("yyyyMMdd").format(yest));
        RequestInfo requestInfo = new RequestInfo(path, format);
        requestInfo.setHeaders(headers);
        requestInfo.setQueryParams(params);
        requestInfo.setBody(body);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String currDay = new SimpleDateFormat("yyyyMMdd").format(curr);
        requestInfo.setQueryParam("token", byte2hex(md5.digest(("ipubtrans" + currDay).getBytes(StandardCharsets.UTF_8))));
        return requestInfo;
    }

    private Date getYest() {
        Calendar yest = Calendar.getInstance();
        yest.setTime(new Date());
        yest.add(Calendar.DATE, -1);
        return yest.getTime();
    }

    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (byte value : b) {
            //为了保证二进制机器数不变，这里需要& 0XFF
            stmp = (Integer.toHexString(value & 0XFF));
            //如果只有一位，需要在前面补上0凑足两位
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }
        return hs.toString();
    }
}
